/**
 * Mi-Alert
 *
 * @author Ma Jing<majing@oneapm.com>
 * created at 2016-02-25
 */
import React from 'react';
import cx from 'classnames';
import _ from 'underscore';

import View from 'lib/View.jsx';
import dispatcher from 'lib/dispatcher'
import Card from 'lib/components/card.jsx';
import Modal from 'lib/components/Modal.jsx';
import GridWidget from 'lib/components/GridWidget.jsx'
import ApiFactory from 'lib/ApiFactory';
import {Success,Info,Warning} from 'lib/components/Notify.jsx'
import {Confirm} from 'lib/components/Confirm.jsx'
import {ConfirmGreen} from 'lib/components/ConfirmGreen.jsx'

import Layout from '../common/layout.jsx';
import {request} from '../apis/core-util';

import MainScope from './MainScope.es6';
import AlertEditor from './AlertEditor.jsx';

/**
 * [getCookieByName]
 * @param  {[string]} objname [name used to search cookie]
 * @return {[string]}         [cookie value according to @param name]
 */
// function BlueWare.sessionIde) {
//   var arrstr = document.cookie.split("; ");
//   for (var i = 0; i < arrstr.length; i++) {
//     var temp = arrstr[i].split("=");
//     if (temp[0] == objname) {
//       return unescape(temp[1])
//     };
//   }
// }

export default class MainView extends View {
  constructor(props) {
    super(props);
    this.add = this.add.bind(this);
    this.handleKeywordChange = this.handleKeywordChange.bind(this);

    this.gridColumns = [
      {
        title: '状态',
        key: 'alarmStatus',
        width: '10%',
        sortable: true,
        render: function(fmtVal, rowData) {
          //警报状态 1、ALERT 2、WARN 3、OK 4、NO DATA
          let status = {
            1: 'ALERT',
            2: 'WARNING',
            3: 'OK',
            4: 'NO DATA'
          };
          return (rowData.isMuted === 1) ?
            (
              <p>
                <a className="btn-gray btn-xs btn-disabled">禁用</a>
              </p>
            ) :
            (
              <p>
                <a className={cx({
                  'btn-red btn-xs': rowData.alarmStatus === 1,
                  'btn-yellow btn-xs': rowData.alarmStatus === 2,
                  'btn-green btn-xs': rowData.alarmStatus === 3,
                  'btn-gray btn-xs': rowData.alarmStatus === 4
                })}>
                {
                  status[rowData.alarmStatus]
                }
                </a>
              </p>
            )
        }
      },
      {
        title: '名称',
        key: 'alarmName',
        width: '16%',
        sortable: true,
        render: (fmtVal,rowData) => (
          <a href={'http://c.110monitor.com/console//alarm/index.jsp?JSESSIONID='+BlueWare.sessionId} target="__blank">
            { rowData.alarmName }
          </a>)
      },
      {
        title: '监控项',
        key: 'alarmType',
        width: '14%',
        sortable: true,
        render: (fmtVal, rowData) => rowData.alarmType === 1 ? 'APP' : '--'
      },
      {
        title: '吞吐量',
        key: 'cpm',
        width: '10%',
        sortable: true,
        render: (fmtVal,rowData) => (<div> >= { rowData.cpm }</div>)
      },
      {
        title: '报警条件',
        key: 'rules',
        sortable: true,
        width: '25%',
        render: function(fmtVal, rowData) {
          let list = [];
          let rules = rowData.rule;
          let ruleTypes = {
            1: '响应时间',
            2: '崩溃率',
            3: 'HTTP错误率',
            4: '网络错误率'
          };
          for (let i = 0; i < rules.length; i++) {
            // 1、数值 2、频率 3、无事件
            if (rules[i].criteria[1].criteriaType === 1) {
              list.push(`${ruleTypes[rules[i].ruleType]}： > ${rules[i].criteria[1].threshold}ms`)
            }
            else if (rules[i].criteria[1].criteriaType === 2) {
              list.push(`${ruleTypes[rules[i].ruleType]}： > ${rules[i].criteria[1].threshold}%`)
            }
          }

          let result = [];
          let tmp = [];
          for (let i = 0; i < list.length; i++) {
            if (tmp.length !== 2) {
              tmp.push(list[i]);
            }
            if (tmp.length === 2) {
              result.push(tmp);
              tmp = [];
            }
          }
          if (tmp.length === 1) {
            result.push(tmp);
          }

          let maxLenght = _.max(list, p => p.length).length;
          let colSpan = list.length > 1 ? 2 : 1;
          return (
            <table className="table table-reduced no-hover" style={{ width: 300 }}>
              <tbody>
              {
                result.map((item, index) => (
                  item.length === 2
                    ? (
                      <tr className="pure-g" key={ index }>
                        <td className="pure-u-1-2">{ item[0] }</td>
                        <td className="pure-u-1-2">{ item[1] }</td>
                      </tr>
                    ) : (
                      <tr className="pure-g" key={ index }>
                        <td className="pure-u-1" colSpan={ colSpan }>{ item[0] }</td>
                      </tr>
                    )
                ))
              }
              </tbody>
            </table>
          )
        }
      },
      {
        title: '创建人',
        key: 'createUserName',
        // width: "10%",
        sortable: true,
        render: (fmtVal, rowData) => rowData.createUserName
      },
      {
        title: '操作',
        key: 'action',
        width: 66,
        render: (fmtVal, rowData) => {
          return (
            <div className="operation" style={{ textAlign: 'left' }}>
              <a
                onClick={this.updatePolicy.bind(this, rowData)}
                href="javascript:;"
                className="iconfont">
                &#xe637;
              </a>
              <a
                onClick={this.mutePolicy.bind(this, rowData)}
                href="javascript:;"
                style={{ margin: '0 8px' }}
                className="iconfont">
                &#xe6d2;
              </a>
              <a onClick={ this.deletePolicy.bind(this, rowData.alarmName) }
                href="javascript:;"
                className="iconfont">
                &#xe61f;
              </a>
            </div>
          )
        }
      }
    ]; // gridColumns
  }

  deletePolicy(alarmName) {
    Confirm('确定要删除 "' + alarmName + '" 报警策略吗？').then(()=>{
      // debugger
      request(BlueWare.urlPrefix+'/app/'+BlueWare.appId+'/deleteAlarmStrategy.json?alarmName='+alarmName, 'delete').then(function(res){
          if(res.status === 0){
            Success('删除成功！')
            dispatcher.dispatch({
              $type:'refresh_grid'
            })
          }else{
            Warning('删除失败！！')
          }
        },function(){
          Warning('删除失败！')
        })
    })
  } // deletePolicy

  mutePolicy(policy) {
    if (policy.isMuted === 0) {
      Confirm('禁用后将不再收到报警信息，确定要禁用 "' + policy.alarmName + '" 报警策略吗？').then(()=>{
        // debugger
        request(BlueWare.urlPrefix+'/app/'+BlueWare.appId+'/updateAlarmMuted.json?alarmName='+policy.alarmName+'&isMuted=1', 'put').then(function(res){
            if(res.status === 0){
              Success('操作成功！')
              dispatcher.dispatch({
                $type:'refresh_grid'
              })
            }else{
              Warning('操作失败！！')
            }
          },function(){
            Warning('操作失败！')
          })
      })
    }
    else if (policy.isMuted === 1) {
      ConfirmGreen('"' + policy.alarmName + '" 报警策略当前为禁用状态，点击确定可解除禁用').then(()=>{
        // debugger
        request(BlueWare.urlPrefix+'/app/'+BlueWare.appId+'/updateAlarmMuted.json?alarmName='+policy.alarmName+'&isMuted=0', 'put').then(function(res){
            if(res.status === 0){
              Success('操作成功！')
              dispatcher.dispatch({
                $type:'refresh_grid'
              })
            }else{
              Warning('操作失败！！')
            }
          },function(){
            Warning('操作失败！')
          })
      })
    }
  } // mutePolicy

  updatePolicy(policy) {
    AlertEditor.mount(_.extend({}, policy, {
      isNew: false,
      onCompleted: () => dispatcher.dispatch({
        $type:'refresh_grid'
      })
    }));
  } // updatePolicy

  add() {
    AlertEditor.mount({
      draggable: true,
      isNew: true,
      onCompleted: () => dispatcher.dispatch({
        $type:'refresh_grid'
      })
    })
  }

  handleKeywordChange(e) {
    if (e.which === 13) {
      dispatcher.dispatch({
        $type: 'search_keyword',
        value: e.target.value.toLowerCase().trim()
      });
    }
  } // handleKeywordChange

  handleTypeChangeHandler(targetType) {
    dispatcher.dispatch({
      $type: 'type_changed',
      searchKeyword: this.refs.keyword.value.trim(),
      targetType
    })
  } // handleTypeChangeHandler

  render() {
    return (
      <Layout title="警报策略" subtitle="设置值得关注的报警策略" hideTime={ true } hideVersion={ true }>
        <div className="pure-g">
          <div className="pure-u-1">
            <div className="box">
              <Card title="告警触发器列表" extra={
                <div>
                  <a href={'http://c.110monitor.com/console//user/List.jsp?JSESSIONID='+BlueWare.sessionId} target="__blank">
                    <i className="iconfont">
                    <span className="icon">&#xe633;</span>
                    <span className="text">设置告警组</span>
                    </i>
                  </a>
                </div>
              }>
                <div className="search-row">
                  <input
                    className="input-text search-box"
                    ref="keyword"
                    type="text"
                    name="alarmName"
                    onKeyPress={ this.handleKeywordChange }
                    placeholder={ 'Search' } />
                  <button className="btn-green float-right" type="button" onClick={ this.add }>
                    添加告警策略
                  </button>
                </div>

                <div className="button-row">
                  <button
                    className={cx('btn-xs btn-bold btn-blue', {
                      'btn-hollow': this.state.alarmStatus !== 0
                    })}
                    onClick={ this.handleTypeChangeHandler.bind(this, 0) }>ALL
                  </button>
                  <button
                    className={cx('btn-xs btn-bold btn-green', {
                      'btn-hollow': this.state.alarmStatus !== 3
                    })}
                    onClick={ this.handleTypeChangeHandler.bind(this, 3) }>OK
                  </button>
                  <button
                    className={cx('btn-xs btn-bold btn-yellow', {
                      'btn-hollow': this.state.alarmStatus !== 2
                    })}
                    onClick={ this.handleTypeChangeHandler.bind(this, 2) }>WARNING
                  </button>
                  <button
                    className={cx('btn-xs btn-bold btn-red', {
                      'btn-hollow': this.state.alarmStatus !== 1
                    })}
                    onClick={ this.handleTypeChangeHandler.bind(this, 1) }>ALERT
                  </button>
                  {/*<button
                    className={cx('btn-xs btn-bold', {
                      'btn-gray': !this.state.isProcessing,
                      'btn-hollow': this.state.alarmStatus !== 1,
                      'btn-disabled': this.state.isProcessing
                    })}
                    disabled={ this.state.isProcessing }
                    onClick={ this.handleTypeChangeHandler.bind(this, 1) }>禁用</button>*/}
                </div>
                <GridWidget cols={ this.gridColumns } store={ this.state.grid } />
              </Card>
            </div>
          </div>
        </div>
      </Layout>
    );
  }

}

MainView.defaultProps = {
  Scope: MainScope
}
